/* 
 * File:   AreaLight.cpp
 * Author: brady
 * 
 * Created on August 24, 2011, 6:43 PM
 */

#include <lights/AreaLight.h>

AreaLight::AreaLight() {
}

AreaLight::AreaLight(const Vector3D& origin, const Vector3D color){
    this->origin = origin;
    this->color = color;
}

AreaLight::AreaLight(const AreaLight& orig) {
    this->origin = orig.origin;
    this->color = orig.color;
}

AreaLight::~AreaLight() {
}

Vector3D AreaLight::getSamplePoint(const IntersectionResult& result) const{
    //Build an orthonormal basis
    if(gParams.initialSamples == 1) return origin;
    
    Vector3D u;
    Vector3D v;
    Vector3D w;
    Vector3D up(0,1,0);
    w = (result.hitPoint - origin);
    w.normalize();
    u = up.cross(w).normalize();
    v = w.cross(u).normalize();

    //the number of rows and columns to divide the pixel into
    int subDivisions = (int) sqrt((float)gParams.initialSamples);

    double left, top, lightWidth, lightHeight;
    lightWidth = size;
    lightHeight = size;
    left = -lightWidth/2.0;
    top = -lightHeight/2.0;

    int col = result.ray.sampleNumber%subDivisions;
    int row = result.ray.sampleNumber/subDivisions;

    double subDivisionSize = (double)size/(double)subDivisions;

    double xOffset = left + col*subDivisionSize + ((double)random()/(double)RAND_MAX)*subDivisionSize;
    double yOffset = top + row*subDivisionSize + ((double)random()/(double)RAND_MAX)*subDivisionSize;
    
    return (origin + (u*xOffset) + (v*yOffset));
}